package javbot.command;

import java.awt.AWTException;
import java.awt.event.KeyEvent;

public class CmdPressKey extends Command {
	
	final int[] keys;
	
	public CmdPressKey(int keys[]) throws AWTException {
		super();
		this.keys = keys;
	}
	
	public CmdPressKey(int key) throws AWTException {
		super();
		this.keys = new int[] {key};
	}	
	
	public CmdPressKey(String keyLine) throws AWTException {
		String splitKeys[] = keyLine.trim().split(",");
		
		keys = new int[splitKeys.length];
		for (int i=0; i <splitKeys.length; i++) {
			String key = splitKeys[i].trim();
			String key_lc = splitKeys[i].trim().toLowerCase();
			if (key_lc.equals("space")) {
				keys[i] = KeyEvent.VK_SPACE;
			}
			else if (key_lc.equals("alt")) {
				keys[i] = KeyEvent.VK_ALT;
			}
			else if (key_lc.equals("ctrl")) {
				keys[i] = KeyEvent.VK_CONTROL;
			}
			else if (key_lc.equals("shift")) {
				keys[i] = KeyEvent.VK_SHIFT;
			}
			else if (key_lc.equals("tab")) {
				keys[i] = KeyEvent.VK_TAB;
			}
			else if (key_lc.equals("winkey")) {
				keys[i] = KeyEvent.VK_WINDOWS;
			}
			else if (key_lc.equals("esc")) {
				keys[i] = KeyEvent.VK_ESCAPE;
			}
			else if (key_lc.equals("backspace")) {
				keys[i] = KeyEvent.VK_BACK_SPACE;
			}
			else if (key_lc.equals("enter")) {
				keys[i] = KeyEvent.VK_ENTER;
			}						
			else {
				keys[i] = key.charAt(0);
			}
		}
	}		

	public void execute() {
		for (int i=0; i< keys.length; i++) {
			robot.keyPress(keys[i]);
		}

		for (int j=keys.length-1; j >= 0; j--) {
			robot.keyRelease(keys[j]);
		}		
	}

	public String toString() {
		String s = "Key " + KeyEvent.getKeyText(keys[0]);
		for (int i=1; i< keys.length; i++) {
			s += ", " + KeyEvent.getKeyText(keys[i]);
		}		
		return s;
	}

}
